﻿// For an introduction to the HTML Fragment template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
	"use strict";


	String.prototype.startsWith = function(str){
		return (str && this.substr(0, str.length) === str);
	};


    var search = {
    	source: 'http://bing.com',
    	isReady: false,

    	init: function () {
    		// if image is from previous day, get new image

    		if (!search.image) { search.getPage(); }

    		// set timer to update image daily
    	},
    	ready: function (element, options) {
    		search.$main = $('#search');
    		search.showImage();
    	},


    	updateLayout: function (element, viewState) { },


    	getPage: function () { WinJS.xhr({ url: search.source }).then(search.onSaveImage, search.onError); },

    	onSaveImage: function (result) {

    		if (!result || !result.responseText) { search.onError(result); }
    		var html = result.responseText;  // TODO: .replace(/'\//g, "'" + search.source + '/').replace(/"\//g, '"' + search.source + '/').replace(/url(\//g, 'url(' + search.source + '/');

    		// download "'/" + '"/" + "url(/"
    		// replace "'/" + '"/" + "url(/" with "\0/storage/"
    		// save bing.htm

    		var start = html.indexOf('g_img={');
    		if (start > 0) { start = html.indexOf("'", start) + 1; }
    		var end = html.indexOf("'", start + 1);
    		search.image = html.substr(start, end - start);
    		if (search.image.startsWith('/')) { search.image = search.source + search.image; }
    		search.showImage();

    		/*
			Notification.TileUpdateManager.createTileUpdateForApplication().enableNotificationQueue
			Notification.TileUpdateManager.getTemplateContent(Notifications.TileTemplateType.tileWideSmallImageAndText
			new Notifications.TileNotification(xml)
			Notifications.TileUpdateManager.
			*/
    	},
    	showImage: function () {
    		if (!search.image || search.$main.length == 0) { return; }
    		search.$main.append('<img class="search-bg" src="' + search.image + '"/>');
    		setTimeout(function () { search.$main.children('.search-bg:last').addClass('active'); }, 50);
    	},
    	onError: function (result) { alert('Failed\n' + result.status); }
	};
    search.init();


    WinJS.UI.Pages.define("/html/search.html", {
        ready: search.ready,
        updateLayout: search.updateLayout
    });
})();
